package com.itheima.intercept;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//为登录设置拦截器进行拦截,判断当前用户登录所携带的cookie在redis中是否存在,存在则过去,不存在则提示重新登录
public class MyIntercept implements HandlerInterceptor {
    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                boolean a = cookie.getName().equals("login_telephone_member");
                if (a){
                    String value = cookie.getValue();
                    Jedis resource = jedisPool.getResource();
                    //拿到存在redis缓存中会员member的值
                    String member = resource.get(value);
                    //判断缓存中值是否为null
                    if(member==null){
                        //sh说明用户没有登陆过或者登录过期,则在前台进行说明
                        ServletOutputStream responseOutPutStream = response.getOutputStream();
                        response.setContentType("application/json"); //像前台申明这是json类型
                        responseOutPutStream.write("{\"data\":null,\"flag\":false,\"message\":\"登录过期\"}".getBytes());
                        responseOutPutStream.flush();
                        responseOutPutStream.close();
                        return false;
                  }
                    return true;
                }
            }
        }
        return false;
    }
}
